using System;
using System.Configuration;
using umbraco;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.web;
using umbraco.interfaces;
using umbraco.NodeFactory;

namespace Twins.sandbox.web.EventHandlers
{
	public class Documents : ApplicationBase
	{

		public Documents()
		{
            Document.BeforePublish += Document_BeforePublish;
		}

              /// <summary>
        /// Moves a Post if the Post Date Changes
        /// </summary>
        /// <param name="sender">Document Being Published</param>
        /// <param name="e">Publish Event Args</param>
        void Document_BeforePublish(Document sender, umbraco.cms.businesslogic.PublishEventArgs e)
        {
            if (sender.ContentType.Alias == "NewsPage") //As this runs for every publish event, only proceed if this is BlogPost
            {
                Log.Add(LogTypes.Debug, sender.User, sender.Id, string.Format("Start Before Publish Event for Newsitem {0}", sender.Id));
                if (sender.getProperty("date") != null) //If no post date, skip 
                {
                    if (sender.Parent != null)  //If top of tree, something is wrong.  Skip.
                    {
                        try
                        {
                            DocumentVersionList[] postVersions = sender.GetVersions();
                            bool _versionCheck = true;
                            DateTime postDate;
                            postDate = System.Convert.ToDateTime(sender.getProperty("date").Value);
                            if (postVersions.Length > 1)  //If it has been published, check post date info
                            {
                                //Length -1 is current version Length -2 is past version (if it exists)
                                Guid previousVersion = postVersions[postVersions.Length - 2].Version;
                                Document doc = new Document(sender.Id, previousVersion);
                                DateTime previousPostDate = System.Convert.ToDateTime(doc.getProperty("date").Value);

                                _versionCheck = (postDate != previousPostDate);

                            }

                            if (_versionCheck)  //Only do the date folder movement if the PostDate is changed or is new Post.
                            {
                                string[] strArray = { postDate.Year.ToString(), postDate.Month.ToString(), postDate.Day.ToString() };
                                if (strArray.Length == 3)
                                {
                                    Node topNewsFolder = new Node(sender.Parent.Id);

                                    try
                                    {
                                        //Traverse up the tree to Find the NewsFolder Node since we are likely in a Date Folder path
                                        while (topNewsFolder != null && topNewsFolder.NodeTypeAlias != "NewsFolder")
                                        {
                                            if (topNewsFolder.Parent != null)
                                            {
                                                topNewsFolder = new Node(topNewsFolder.Parent.Id);
                                            }
                                            else
                                            {
                                                topNewsFolder = null;
                                            }
                                        }
                                    }
                                    catch (Exception Exp)
                                    {

                                        Log.Add(LogTypes.Debug, sender.User, sender.Id, string.Format("1111Error while Finding NewsFolders for Newsitem {0} while trying to move to new Post Date.  Error: {1}, parent {2}", sender.Id, Exp.Message, sender.Parent.Id));

                                    }

                            
                                    if (topNewsFolder != null)
                                    {
                                        Document document = null;
                                        Node folderNode = null;

                                        //Search for year folder
                                        foreach (Node ni in topNewsFolder.Children)
                                        {
                                            if (ni.Name == strArray[0])
                                            {
                                                folderNode = new Node(ni.Id);
                                                document = new Document(ni.Id);
                                                break;
                                            }
                                        }

                                        //If it doesent exist create it
                                        if (folderNode == null)
                                        {
                                            document = Document.MakeNew(strArray[0], DocumentType.GetByAlias("DateFolder"), sender.User, topNewsFolder.Id);
                                            document.Publish(sender.User);
                                            library.UpdateDocumentCache(document.Id);
                                            folderNode = new Node(document.Id);
                                        }

                                        //search after month folder
                                        Node folderNode2 = null;
                                        foreach (Node ni in folderNode.Children)
                                        {
                                            if (ni.Name == strArray[1])
                                            {
                                                folderNode2 = new Node(ni.Id);
                                                break;
                                            }
                                        }

                                        //if it doesent exist create it
                                        if (folderNode2 == null)
                                        {
                                            Document document2 = Document.MakeNew(strArray[1], DocumentType.GetByAlias("DateFolder"), sender.User, folderNode.Id);
                                            document2.Publish(sender.User);
                                            library.UpdateDocumentCache(document2.Id);
                                            folderNode2 = new Node(document2.Id);
                                        }

                                        //Search after day folder
                                        Document document3 = null;  //As this is the last check, a document object is fine
                                        foreach (Node ni in folderNode2.Children)
                                        {
                                            if (ni.Name == strArray[2])
                                            {
                                                document3 = new Document(ni.Id);
                                                break;
                                            }
                                        }
                                        //if it doesent exist create it
                                        if (document3 == null)
                                        {
                                            document3 = Document.MakeNew(strArray[2], DocumentType.GetByAlias("DateFolder"), sender.User, folderNode2.Id);
                                            document3.Publish(sender.User);
                                            library.UpdateDocumentCache(document3.Id);
                                        }

                                        //Move the blogpost under the correct day folder
                                        if (sender.Parent.Id != document3.Id)
                                        {
                                            sender.Move(document3.Id);
                                            Log.Add(LogTypes.Debug, sender.User, sender.Id, string.Format("Move Required for Newsitem {0} for PostDate {1}.  Moved Under Node {2}", sender.Id, postDate.ToShortDateString(), document3.Id));
                                        }
                                    }
                                    else
                                    {
                                        Log.Add(LogTypes.Debug, sender.User, sender.Id, string.Format("Unable to determine top of NewsFolder for Newsitem {0} while attempting to move to new Post Date", sender.Id));
                                    }

                                }
                            }
                        }
                        catch (Exception Exp)
                        {
                            Log.Add(LogTypes.Debug, sender.User, sender.Id, string.Format("Error while Finding NewsFolders for Newsitem {0} while trying to move to new Post Date.  Error: {1}, parent {2}", sender.Id, Exp.Message, sender.Parent.Id));
                        }

                        umbraco.library.RefreshContent();
                    }
                }
            }
        }
		
	}
}